<?php
class tsAdminDash {

  /**
   * Get module name by route
   *
   * @param string $url
   */
  public static function getItemByUrl($url) {
    
    foreach (self::getProperty('categories') as $category) {
      
      foreach ($category['items'] as $title => $item) {
        
        if (self::isActive($item)) {
          
          $item['title'] = $title;
          return $item;
        }
      }
      
    }
    return false;
  }
  
  public static function getItems()
  {
    return self::getProperty('items');
  }

  public static function getCategories()
  {
    $categories = self::getProperty('categories');
    
    return self::getProperty('categories');
  }

  public static function getProperty($val)
  {
    return sfConfig::get('app_ts_admin_dash_'.$val);
  }

  public static function hasPermission($item, $user)
  {
    if (!$user->isAuthenticated())
    {
      return true;
    }

    if (!key_exists('credentials', $item))
    {
      return true;
    }

    if ($user->hasCredential($item['credentials']))
    {
      return true;
    }
    else
    {
      return false;
    }
  }
  
  public static function isActive($item) {

    $url = $item['url'];
    
    if (('@' == substr($url, 0, 1) || false !== strpos($url, '/') )) {

      $route = sfContext::getInstance()->getRouting()->findRoute($url); 

    } else {
  
      if (sfContext::getInstance()->getRouting()->hasRouteName($url)) {
    
        $routes = sfContext::getInstance()->getRouting()->getRoutes();
        $route = array(
          'parameters' => $routes[$url]->getDefaults()
        );

      }
    }
    
    return ($route && $route['parameters']['module'] == sfContext::getInstance()->getModuleName());
  }
  
  public static function isOneActive($items) {

    $is_active = false;

    foreach($items as $key => $item) {
      $is_active = self::isActive($item);
      if ($is_active) {
        return $is_active;
      }
    }

    return false;
  }
  
  
}
